<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */ 
namespace app\web\controller;

use app\common\Base;
class User extends Base{
    public $config = [
         // 验证码字体大小
        'fontSize'    =>    30,
    // 验证码位数
        'length'      =>    4,
    // 关闭验证码杂点
        'useNoise'    =>    false,
        'imageH'   =>    85,
        'imageW'   =>    220, 
    ];
    public function UserLogin() { //显示前台用户登录页面的方法
        return $this->view->fetch();
    }
    public function ToPicture() {//生成验证码
        $verify = new \think\captcha\Captcha($this->config);//实例验证码
        return $verify->entry();
    }
    public function UserRegister() { //显示前台页面用户注册的方法
        return $this->view->fetch();
    }
    public function success_login() //作为登录提示，提醒登陆成功，并跳转至网页的问题页面
    {
      $this->success_ui("登录成功~",url('web/Problem/problemset'));
    }
    

    public function JudgeLogin() { //前台AJAX调用，判断用户登录。
      $email = input('post.email');
      $user_id="";
      $db_pass="";
      $judge1 = db('users')->where("email",$email)->find();
      $judge2 = db('users')->where("user_id",$email)->find();
      if(empty($judge1)&& empty($judge2)) {
          return json(['result'=>false]);
      }
      if(!empty($judge1)){
          $user_id=$judge1['user_id'];
          $db_pass=$judge1['password'];
      }
      if(!empty($judge2)){
          $user_id=$judge2['user_id'];
          $db_pass=$judge2['password'];
      }
      $password =get_passwd_string(input('post.password'),$user_id);
      if($password == $db_pass) {
          $_SESSION['user_id']=$user_id;
          return json(['result'=>true]);
      }
      return json(['result'=>false]);
    }

 
    public function ToSendEmail($email,$type) { //根据所传type参数['register'],['forget']发送注册，重置密码邮件
      $str_email = $email;
      $to = $str_email;
      if($type=='register')  {
          $title = 'NYOJ用户注册邮箱验证';
          $html='userregistering';
      } else if($type=='forget'){
          $title = 'NYOJ用户重置密码邮箱验证';
          $html='UpdatePassword';
      }
      $str =config($type). $str_email;
      $body = $to . ", 您好：" . "<br>" . "请您点击下面的链接，完成您在NYOJ的验证";
     // $request = Request->instance();
      // $url = url('web/');
      $tmp_str=$str.time();
      cache("email-".$type.$email,md5($tmp_str),30*60);
      $url=request()->domain() .url('web/User/'.$html,['email'=> $to,'key'=>md5($tmp_str)]);
      //$url = request()->domain() ."/web/user/".$html.".html?key=" . md5("$str") . "&email=" . $to;
      $body = $body .  "<a href='$url'>$url</a>";
      $username = "NYOJ管理员";
      return $this->sendmail($to,$title,$body,$username);
    }


    public function Registered() {//显示前台邮箱已发送成功页面的方法。
        $email = input('email');
        $judge = db('users')->where("email='$email'")->find();
        if(!empty($judge)) {
        echo "<script> alert('此邮箱已被注册!'); </script>";
        } else {
             $this->assign('email',$email);
            return $this->fetch();
        }
    }


    public function Userregistering() { //显示前台根据所发注册邮箱进入注册页面的方法
        $email = $this->remove_xss(input('email'));
        $key = $this->remove_xss(input('key'));
        $code= cache('email-register'.$email);
        if($code!=$key) {
            $this->error_ui('该链接已经失效，请重试');
        }
        $this->assign('key',$key);
        $this->assign('email',$email);
        return $this->fetch();   
    }


    public function JudgeEmail() {//判断邮箱账号是否存在数据库，并发送邮箱
        $verify = input('post.verify');
        if(!captcha_check($verify))  { //验证码不对
          return json(['result'=>-1]);
        }
        $email = input('post.email');
        // dump($email);
        $result = db('users')->where(['email'=>$email])->find();
        $type = input('post.type');
        if(!empty($result)) {//数据库中存在这个邮箱，
            if($type=='forget') {
                $this->ToSendEmail($email,'forget');
            }
            return json(['result'=>1]);
        } else {  //数据库中不存在这个邮箱
            if($type=='register') {
                $res = $this->ToSendEmail($email,'register');
            }
            return json(['result'=>0]);
        }
    }

    // public function update_password() {
    //     $user = db('users')->field('user_id,password')->select();
    //     foreach ($user as $key => &$value) {
    //         $value['password'] = md5(config('login') . $value['password'] . $value['user_id']);
    //         db('users')->update($value);
    //     }
    //     // echo '更新完毕';
    // }

    private function ToAddUser($user) {   //用于创建用户，在创建用户时被调用
        $user['submit'] = 0;     //提交次数
        $user['solved'] = 0;     //解决数量
        $user['defunct'] = 'Y';     //用户是否可用
        $now_time = date("Y-m-d h:i:s",time());
        $user['accesstime'] = $now_time;     //上次登陆时间
        $user['reg_time'] = $now_time; //注册时间
        $user['nick']="你的名字";       //
        $user['language'] = 1;     //上次提交语言
        db('users')->insert($user);
      }

    public function JudgeUserid() { //前台AJAX调用。判断用户名是否可用并创建用户
        $email =input('post.email');
        $codekey= cache('email-register'.$email);
        $key= input('post.key');
        if($key!=$codekey) {
            return json(['result'=>false,'msg'=>'链接错误或已经失效！']);
        }
        $judge= db('users')->where("email='$email'")->find();
        if(!empty($judge)) {  
          return json(['result'=>false,'msg'=>'此邮箱已经被注册！']);
        }
        $password1=input('post.password1');
        $password2=input('post.password2');
        if($password1!=$password2) {
          return json(['result'=>false,'msg'=>'两次密码不一致！']);
        }
        $user = Array();
        $user['user_id'] = input('username');
        if(!preg_match("/^[0-9a-zA-Z\_]+$/",$user['user_id'])) { //正则匹配用户名
            return json(['result'=>false,'msg'=>'用户名只能由数字，字母，下划线组成！']);
        }
        $result = db('users')->where($user)->find();
        if(empty($result)) {
            $user['email'] = $email;
            // md5(config('login').md5(input('post.password')).$user_id[0]['user_id']);
            $user['password'] = md5(config('login') . md5($password1) . $user['user_id']);
            $this->ToAddUser($user);
            return json(['result'=>true]);//可用
      }
        return json(['result'=>false,'msg'=>'此账号已经被注册！']);//不可用*/
    }


    public function SubmitRegister() {  //显示前台提交注册后对应的页面的方法。
        return $this->view->fetch();
      }
    public function Forget() {  //显示前台忘记密码对应的页面的方法。
        return $this->view->fetch();
      }


    public function Toupdate() {  //显示前台发送重置密码的邮件对应的页面的方法
        $str_email=input('email');
        $judge=db('users')->where("email='$str_email'")->find();
        if(empty($judge)) { 
            echo "<script> alert('此邮箱尚未注册！'); </script>";
            return ;
        }
        $this->assign('email',$str_email);
        return $this->fetch();
     }

    public function UpdatePassword() {  //显示前台发送重置邮件后的提示页面的方法
        $email = input('email',null);
        if($email==NULL) exit();
        $key = input('key');
        $keycode=cache('email-forget'.$email);
        if($keycode == $key) {
            $this->assign('key',$key);
            $this->view->assign('email',$email);
            return $this->view->fetch();
        }
        else {
            $this->error_ui('验证码已失效');
        }
    }

     public function use_email_update_password() { //根据发送邮件更新密码

        $email = input('post.email');
        $key = input('post.key');
        $passwd1= input('post.password1');
        $passwd2= input('post.password2');
        if(cache('email-forget'.$email)!=$key) {
            return json(['result'=>false,'msg'=>'链接已失效，请重新发送~']);
        } else {
            if($passwd1 != $passwd2) {
                return json(['result'=>false,'msg'=>'两次密码不一致！']);
            }
            $user = db('users')->where(['email'=>$email])->field('user_id')->find();
            $passwd = md5(config('login').md5($passwd1).$user['user_id']);
            db('users')->update(['user_id'=>$user['user_id'],'password'=>$passwd]);
            cache('email-forget'.$email,NULL);
            return json(['result'=>true,'msg'=>'密码已修改']);
        }
    }


    public function Updateing() { //根据重置邮件更新密码
        return $this->view->fetch();
    }
    public function do_logout(){
        $this->do__logout();
    }
    public function i_am_online(){
        if($this->is_login){
            $data['last_time']=time();
            $data['ip']= request()->ip();
            $res=db('onlineuser')->find($this->user_id);
            //dump($res);
            if($res==NULL){
                $data['user_id']= $this->user_id;
                db('onlineuser')->insert($data);
            } else {
                db('onlineuser')->where('user_id', $this->user_id)->setField($data);
            }
            return json(['code'=>0,'msg'=>'success']);
        }
        else {
            return json(['code'=>1,'msg'=>'您已离线请重新登录']);
        }
    }
    public function onlineuser(){
        $condition['last_time']=['<', time()-21*60];
        db('onlineuser')->where($condition)->delete();
        $list = db('onlineuser')->where(TRUE)->field(['user_id','last_time','ip'])->order('last_time DESC')->select();
        foreach ($list as $k=>$v){
            $list[$k]['head']= $this->GetUserHead($v['user_id']);
            $list[$k]['key']=$k+1;
        }
        $this->assign('list',$list);
        $this->assign('have_power', $this->have_power(8));
        return $this->fetch();
    }
}
